<?php

if_get('/subject_instances', function ()
{/*{{{*/
    list(
        $inputs['subject_id']
    ) = input_list(
        'subject_id'
    );

    $inputs = array_filter($inputs, 'not_null');

    $subject_instances = dao('subject_instance')->find_all_by_column($inputs);

    return [
        'count' => count($subject_instances),
        'subject_instances' => array_build($subject_instances, function ($id, $subject_instance) {
            return [
                null,
                [
                    'id' => $subject_instance->id,
                    'subject_display' => $subject_instance->subject->display_for_subject_instances_subject(),
                    'create_time' => $subject_instance->create_time,
                    'update_time' => $subject_instance->update_time,
                ]
            ];
        }),
    ];
});/*}}}*/

if_post('/subject_instances/add', function ()
{/*{{{*/

    $subject_instance = subject_instance::create(
        input_entity('subject', null, 'subject_id')
    );

    return [
        'id' => $subject_instance->id,
    ];
});/*}}}*/

//todo::detail

if_post('/subject_instances/update/*', function ($subject_instance_id)
{/*{{{*/

    $subject_instance = dao('subject_instance')->find($subject_instance_id);
    otherwise_error_code('SUBJECT_INSTANCE_NOT_FOUND', $subject_instance->is_not_null());

    $subject_instance->subject = input_entity('subject', null, 'subject_id');

    return true;
});/*}}}*/

if_post('/subject_instances/delete/*', function ($subject_instance_id)
{/*{{{*/
    $subject_instance = dao('subject_instance')->find($subject_instance_id);
    otherwise_error_code('SUBJECT_INSTANCE_NOT_FOUND', $subject_instance->is_not_null());

    $subject_instance->delete();

    return true;
});/*}}}*/
